var map;
var intervalId;
var markers = [];
var refreshCount = 0;
var stateIcons = {
	"visible" : "http://icons.iconarchive.com/icons/fatcow/farm-fresh/32/emotion-pumpkin-icon.png",
	"hidden" : "http://icons.iconarchive.com/icons/fatcow/farm-fresh/32/thumb-up-icon.png"
};

google.maps.event.addDomListener(window, 'load', initialize);

function initialize() {
	var mapOptions = {
		zoom : 13,
		center : new google.maps.LatLng(45.634915, 5.562628)
	};
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	canvas = document.getElementById('map-canvas');
	// initializeCountdown();
	jQuery(document).bind('markerUpdated', logMarkerUpdated);
}

function logMarkerUpdated(e, marker) {
	console.info("Event is: ", e);
	console.info("Custom data is: ", marker);
}

function initializeCountdown() {
	// The URL for the .swf file that shows the specified trick.
	var url = "https://sites.google.com/site/demopatabroux/demo-javascript/bomb-countdown.swf";

	// Play .swf file.
	/*
	 * gadgets.flash.embedFlash(url, "countdown-container", { swf_version: 6,
	 * id: "flashid", width: 200, height: 100 });
	 */
}

function addMarker(name, latlng, image) {

	var marker = new google.maps.Marker({
		position : latlng,
		map : map,
		title : name,
		icon : image
	});

	markers.push(marker);
	return marker;
}

function makeJSONRequest() {
	var select = "SELECT Name, Location, State FROM 1BH-HYk4NoUOm2YmEEINX3CkEujNeaxxF6BfJegLT";
	var query = encodeURIComponent(select);
	var url = "https://www.googleapis.com/fusiontables/v1/query?key=AIzaSyBWetFgcTzygZTQhmIj8LsvqUA8Z5mJObE&sql="
			+ query + "&nocache=" + new Date().getTime();
	$.getJSON(url, response);
}

function response(data) {
	var rows = data.rows;

	if (refreshCount == 0) {
		initMarkers(rows);
	} else
		updateMarkers(rows);

	refreshCount += 1;
};

function initMarkers(feed) {
	for ( var key in feed) {
		var item = feed[key];
		var coords = item[1].split(',');
		var latlng = new google.maps.LatLng(coords[0], coords[1]);
		var state = item[2];
		var image = stateIcons[state];
		var marker = addMarker(item[0], latlng, image);
	}
}

function startInterval() {
	clearMarkers();
	refreshCount = 0;
	refreshMap();
	intervalId = window.setInterval(function() {
		refreshMap();
	}, 10000);
}
function stopInterval() {
	window.clearInterval(intervalId);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
	for ( var i = 0; i < markers.length; i++) {
		markers[i].setMap(map);
	}
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
	setAllMap(null);
}

// Shows any markers currently in the array.
function showMarkers() {
	setAllMap(map);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
	clearMarkers();
	markers = [];
}

function refreshMap() {
	makeJSONRequest();
}

function updateMarkers(feed) {
	var name = "";

	for ( var key in feed) {
		var item = feed[key];
		name = item[0];
		state = item[2];

		for ( var i = 0; i < markers.length; i++) {
			var marker = markers[i];

			if (name == marker.getTitle()) {
				if (marker.getIcon() != stateIcons[state]) {
					marker.setIcon(stateIcons[state]);
					fireMarkerUpdatedEvent(marker);
					/*
					 * var infowindow = new google.maps.InfoWindow({ content:
					 * marker.getTitle() }); infowindow.open(map,marker);
					 */
				}
				break;
			}
		}
	}
}

function fireMarkerUpdatedEvent(marker) {
	jQuery(document).trigger('markerUpdated', marker);
}